<template>
  <div class="kcfb-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="custom">自定义时间</el-radio-button>
      </el-radio-group>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        :disabled="quickRange !== 'custom'"
        style="margin-left:12px;width:420px"
      />
      <el-input v-model="query.goodsOrCategory" placeholder="物品/类别" style="width:200px;margin-left:12px" clearable />
      <el-button type="primary" style="margin-left:12px" @click="loadAll()">生成报表</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <div class="chart-wrap">
      <div ref="chartRef" class="chart"></div>
    </div>

    <div class="table-actions">
      <el-button @click="loadTable()">刷新</el-button>
      <el-button @click="onExport">导出</el-button>
    </div>

    <el-table :data="tableData" border style="width:100%" height="520">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="warehouseName" label="仓库名称" min-width="160" />
      <el-table-column prop="quantity" label="库存数量" width="120" />
      <el-table-column prop="amount" label="库存金额" width="140">
        <template #default="{ row }">{{ formatMoney(row.amount) }}</template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10,20,50,100]"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        @size-change="loadTable(1)"
        @current-change="loadTable"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { onMounted, ref, reactive, watch, nextTick } from 'vue'
import { fetchKcfbPage, fetchKcfbChart, type GetInventoryDistributionInput } from '/@/api/report/kcfb'

const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const quickRange = ref<'today'|'yesterday'|'week'|'month'|'custom'>('month')
const dateRange = ref<[string,string]|null>(null)
const query = reactive<{ goodsOrCategory?: string }>({})

const chartRef = ref<HTMLDivElement | null>(null)
let chart: echarts.ECharts | null = null

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'today': return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': { const y = now.subtract(1,'day'); return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')] }
    case 'week': return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'month': return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    default: return dateRange.value ?? null
  }
}

function buildPayload(p = page.value): GetInventoryDistributionInput {
  const range = computeRange()
  return {
    startTime: range?.[0],
    endTime: range?.[1],
    goodsOrCategory: query.goodsOrCategory,
    page: p,
    pageSize: pageSize.value,
  }
}

async function loadChart() {
  const payload = buildPayload()
  const res = await fetchKcfbChart(payload)
  // 兼容两层 result 的后端返回结构
  const data = res?.data?.result?.result ?? res?.data?.result ?? res?.data ?? {}
  await nextTick()
  if (!chart) chart = echarts.init(chartRef.value as HTMLDivElement)
  const option: echarts.EChartsOption = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['数量','金额'] },
    xAxis: { type: 'category', data: data.x || [] },
    yAxis: [
      { type: 'value', name: '数量' },
      { type: 'value', name: '金额', position: 'right' },
    ],
    series: [
      { name: '数量', type: 'bar', data: data.quantity || [], yAxisIndex: 0 },
      { name: '金额', type: 'line', data: data.amount || [], yAxisIndex: 1, smooth: true },
    ]
  }
  chart.setOption(option)
}

async function loadTable(p?: number) {
  if (p) page.value = p
  const payload = buildPayload()
  const res = await fetchKcfbPage(payload)
  // 兼容两层 result，保持与其它报表一致
  const pageData = res?.data?.result?.result ?? res?.data?.result ?? res?.data ?? {}
  tableData.value = pageData.items || []
  total.value = pageData.total || 0
}

async function loadAll() { await Promise.all([loadChart(), loadTable(1)]) }

function reset() {
  quickRange.value = 'month'
  dateRange.value = null
  query.goodsOrCategory = undefined
  loadAll()
}

function onQuickRange() { if (quickRange.value !== 'custom') dateRange.value = null; loadAll() }

function onExport() { /* 预留导出 */ }

function formatMoney(n: number) { return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0) }

onMounted(() => { loadAll() })

watch(pageSize, () => loadTable(1))
</script>

<style scoped>
.kcfb-report { padding: 12px; }
.toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.chart-wrap { background: #fff; padding: 8px; border-radius: 4px; }
.chart { width: 100%; height: 360px; }
.table-actions { margin: 12px 0; }
.pager { margin-top: 10px; display: flex; justify-content: flex-end; }
</style>


